<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<script type="text/javascript" src="/js/jquery.js" th:src="@{/js/jquery.js}"></script>
<script type="text/javascript" src="/js/spark-md5.min.js" th:src="@{/js/spark-md5.min.js}"></script>
<script type="text/javascript" src="/js/base.js" th:src="@{/js/base.js}"></script>
<script type="text/javascript" src="/js/crypto-js.min.js" th:src="@{/js/crypto-js.min.js}"></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/js-md5/0.7.3/js-md5.min.js"></script>-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/jsSHA/3.3.1/sha.min.js"></script>-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>-->

<input type="file" name="file" id="file">

<button id="callApiButton">播放</button>
<script>
    //播放视频
    $(document).ready(function () {
        // 当按钮被点击时
        $('#callApiButton').on('click', function () {
            let videoInfoData = localStorage.getItem("videoInfo");
            console.log("当按钮被点击时" + videoInfoData);
            var videoInfo = JSON.parse(videoInfoData);
            console.log("当按钮被点击时" + videoInfo);
            // 调用API接口
            $.ajax({
                url: baseUrl + "/minio/viewVideo", // 替换为你的API接口URL
                type: "GET",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                data: JSON.stringify({
                    bucketName: videoInfo.bucketName,
                    objectName: videoInfo.url,
                }),
                async: false, //异步
                success: function (response) {
                    // 成功获取数据后的回调函数
                    console.log('接口响应:', response);
                    // 处理返回的数据
                },
                error: function (error) {
                    // 请求失败的回调函数
                    console.error('请求失败:' + error);

                }
            });
        });
    });


    /**
     * 分块计算文件的md5值
     * @param file 文件
     * @param chunkSize 分片大小
     * @returns Promise
     */
    function calculateFileMd5(file, chunkSize) {
        return new Promise((resolve, reject) => {
            let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
            let currentChunk = 0;
            let fileReader = new FileReader();

            fileReader.onload = function (e) {
                var file = e.target.files[0];
                var reader = new FileReader();
                reader.onload = function (e) {
                    var bytes = CryptoJS.lib.WordArray.create(e.target.result);
                    var hash = CryptoJS.SHA256(bytes).toString();
                    console.log("*****hash*****" + hash)
                };
                reader.readAsArrayBuffer(file);

            };

            fileReader.onerror = function (e) {
                reject(e);
            };

            function loadNext() {
                let start = currentChunk * chunkSize;
                let end = start + chunkSize;
                if (end > file.size) {
                    end = file.size;
                }
                fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
            }

            loadNext();
        });
    }

    /**
     * 分块计算文件的md5值，默认分片大小为2097152（2M）
     * @param file 文件
     * @returns Promise
     */
    function calculateFileMd5ByDefaultChunkSize(file) {

        return calculateFileMd5(file, 16777216);
    }

    /**
     * 获取文件的后缀名
     */
    function getFileType(fileName) {
        return fileName.substr(fileName.lastIndexOf(".") + 1).toLowerCase();
    }

    // 文件选择之后就计算文件的md5值
    document.getElementById("file").addEventListener("change", function () {
        let file = this.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var bytes = CryptoJS.lib.WordArray.create(e.target.result);
            var md5 = CryptoJS.SHA256(bytes).toString();
            checkMd5(md5, file);
        };
        reader.readAsArrayBuffer(file);

    });

    /**
     * 根据文件的md5值判断文件是否已经上传过了
     *
     * @param md5 文件的md5
     * @param file 准备上传的文件
     */
    function checkMd5(md5, file) {

        console.log("md5:" + md5);
        console.log("name:" + file.name);
        console.log("fileSize:" + file.size);

        // 请求数据库，查询md5是否存在
        $.ajax({
            url: baseUrl + "/minio/startChunkUpload",
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            data: JSON.stringify({
                fileName: file.name,
                fileSize: file.size,
                digest: md5,
                digestAlgorithm: "SHA-256"
            }),
            async: true, //异步
            success: function (msg) {
                console.log(msg);
                // 文件已经存在了，无需上传
                if (msg.data.exist !== null) {
                    console.log("文件已经存在了，无需上传")
                    var url = msg.data.exist;
                    //这里拿到url就可以和业务绑定了
                    console.log(url);
                } else if (msg.data.exist === null) {
                    // 文件不存在需要上传
                    console.log("文件不存在需要上传")
                    PostFile(file, md5, msg);
                } else {
                    console.log('未知错误');
                }
            },
            error: function (msg) {
                console.log(msg)
            }
        })
    }

    /**
     * 执行分片上传
     * @param file 上传的文件
     * @param i 第几分片，从0开始
     * @param md5 文件的md5值
     */
    function PostFile(file, md5, msg) {


        let size = file.size;
        let id = msg.data.id;
        let chunkSize = msg.data.chunkSize;
        let nextChunkId = msg.data.nextChunkId;
        let instanceId = msg.data.instanceId;

        console.log("…………nextChunkId…………" + nextChunkId)
        while (nextChunkId > 0) {
            let from = (nextChunkId - 1) * chunkSize;
            let to = Math.min(from + chunkSize, size);
            let chunk = file.slice(from, to);
            let chunkId = nextChunkId;
            let form = new FormData();
            form.append("x-chunkUpload-id", id);
            form.append("x-chunkUpload-size", to - from);
            form.append("x-chunkUpload-chunkId", chunkId);
            form.append("Content-Type", "application/octet-stream");
            form.append("x-route-startegy", "instance-id: " + instanceId);
            form.append("file", chunk);

            $.ajax({
                url: baseUrl + "/minio/chunkUpload",
                type: "POST",
                data: form,
                //timeout:"10000",  //超时10秒
                async: false, //异步
                dataType: "json",
                processData: false,
                contentType: false,
                success: function (msg) {
                    console.log(msg);
                    /*  表示上一块文件上传成功，继续下一次  */
                    if (msg.code === "D00000") {
                        nextChunkId = msg.data.nextChunkId;
                    }
                },
                error: function (msg) {
                    console.log(msg)
                }
            })
        }
        //全部上传完 合并请求
        if (nextChunkId === -1) {
            $.ajax({
                url: baseUrl + "/minio/completeChunkUpload",
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify({
                    id: msg.data.id,
                }),
                success: function (msg) {
                    console.log(msg);
                    let bucketName = msg.data.bucketName;
                    let url = msg.data.url;
                    var videoInfo = {
                        bucketName: bucketName,
                        url: url
                    }

                    localStorage.setItem("videoInfo", JSON.stringify(videoInfo))
                    /*  表示上一块文件上传成功，继续下一次  */
                    if (msg.code === "D00000") {
                        console.log("合并成功")
                    } else {
                        console.log("上传错误");
                    }
                },
                error: function (msg) {
                    console.log(msg)
                }
            })
        }
    }
</script>

</body>
</html>

